package nl.miraclebenelux.callerid;

import java.io.IOException;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.*;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPFailureException;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

// http://www.iso.org/iso/english_country_names_and_code_elements
// http://en.wikipedia.org/wiki/International_mobile_phone_codes




@SuppressWarnings("serial")
public class CalleridServlet extends HttpServlet {
	
	public static String removeChar(String s, char c) {
		   String r = "";
		   for (int i = 0; i < s.length(); i ++) {
		      if (s.charAt(i) != c) r += s.charAt(i);
		      }
		   return r;
		}
	
    private static final String Boundary = "--7d021a37605f0";
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		   String img = null;
		   String var[] = null;
		   String val[] = null;
		   //String out = "";
		   String outformat = req.getParameter("output");
		   String temp = req.getParameter("number");
		   String full = req.getParameter("full");
		   String number = temp.trim();
		   String name = "Not Found (" + number + ")";
		   String iso = "";
		   char phone = 'L';
	       String street = "";
	       String place = "";
	       String country = "Not Found";
	       String url = null;
	       String outLine;
	       String expr = null;
	       String zip = "";
	       int iplace = 0;
	       int istreet = 0;
	       int iname = 0;
	       int izip = 0;
	       int output = 1;
	       
	       if (outformat == null || outformat.equalsIgnoreCase("text"))
	       {
	    	   // default
	    	   
	       }
	       else if (outformat.equalsIgnoreCase("json"))
	       {
	    	   output = 2;
	       }
	       else if (outformat.equalsIgnoreCase("xml"))
	       {
	    	   output = 3;  
	       }
	       else if (outformat.equalsIgnoreCase("csv"))
	       {
	    	   output = 4;   
	       }
	       
	       
	       if (!number.isEmpty())
	       { 
	    	  number = removeChar(number,'+');
	    	  number = removeChar(number,' ');
	    	  number = removeChar(number,'(');
	    	  number = removeChar(number,')');
	    	  number = removeChar(number,'-');
	    	  number = removeChar(number,'.');
	    	  sendIM(number);
	          if (number.startsWith("1242"))
	          {
	    	      // Bahamas
	          }
	          else if (number.startsWith("1671"))
	          {
	    	      // Guam
	          }
	          else if (number.startsWith("5399"))
	          {
	    	      // Guantanamo Bay
	          } //819,418,450,438,819,514,867,204,250,604,780,403,709
	          else if (number.startsWith("1"))
	          {
	        	 boolean canada = false;
	        	 String ca[] = {"819","418","450","438","514","867", "204","250","604","780","403","709"};
	        	 for (String temp1: ca)
	               {
		               if (number.startsWith(temp1, 1))
		               {
		        	      canada = true;
		        	      break;
		               }
	               }
                 if (canada)
                 {
                	 country = "Canada";
                	 iso     = "CA";
                	 url     = "http://www.whitepages.ca/search/ReversePhone?full_phone=";
                	 expr    = "<h3 class=\"fn n listing_name\">\\s<span style=\"position: relative;\">";
                	 iname   = 1;
                	 istreet = 0;
                	 izip    = 0;
                	 iplace  = 2;
                	 //          <h3 class="fn n listing_name">
                     //           <span style="position: relative;">
                 }
                 else 
                 {
	        	    country = "USA";
	        	    iso     = "US";
	        	    url     = "http://www.whitepages.com/search/ReversePhone?full_phone=" + number.substring(1);
	        	    expr    = "address: \"([^\"]+)\", name: \"([^\"]+)\"";
	        	    iname   = 2;
	        	    istreet = 1;
	        	    izip    = 0;
	        	    iplace  = 0;
                 }
	        //	 country: 'US', state: 'CA US', city: 'Novato CA', address: "6 Hamilton Lndg, Novato, CA  94949-8264, US", name: "Sheila Dahlgren",
	          }
	          else if (number.startsWith("20"))
	          {
	    	     // Egypt
	          }
	          else if (number.startsWith("30"))
	          {
	             // Greece
	    	     country = "Greece";
	          }
	          else if (number.startsWith("31"))
	          {
	           // +31 6, +31 62, +31 63, +31 64, +31 65, +31 650, +31 651, +31 653, +31 654, +31 655, +31 66, +31 67, +31 68, +31 69, +31 80, +31 85, +31 9
	           // Netherlands
	           String mob[] = {"62","63","64","650","651","652","653","654","655","66", "67", "68","69", "6", "80", "85", "9"};
               for (String tempmob: mob)
               {
	               if (number.startsWith(tempmob, 2))
	               {
	        	      phone = 'M';
	        	      break;
	               }
               }
	    	   country = "Netherlands";
	    	   iso     = "NL";
	    	   url = "http://www.nummerzoeker.com/?color=white&lastname=&str=&hnr=&pc=&pl=&phone=0" + number.substring(2) + "&maxrows=1&sort=1&search=Zoeken";
	    	   expr = "</td>\\s+<td class=\"nowrap\">.*?<td>([^<]+)</td>\\s+<td class=\"nowrap\">([^<]+)</td>\\s+<td class=\"nowrap\">([^<]+)</td>\\s+<td class=\"nowrap\">([^<]+)</td>";	    	   
	    	   iname = 1;
	    	   istreet = 2;
	    	   izip = 3;
	    	   iplace = 4;
	          }
	          else if (number.startsWith("32"))
	          {
	              // Belgium
	        	  // +32 16, +32 17, +32 47, +32 49, +32 7, +32 98
	        	  String mob[] = {"16","17","47","49","7","98"};
	        	  for (String tempmob: mob)
	        	  {
	        		  if (number.startsWith(tempmob, 2))
	   	              {
	   	        	     phone = 'M';
	   	        	     break;
	   	              }
	        	  }
	    	      country = "Belgium";
	    	      iso     = "BE";
	    	      val     = new String[5];
	    	      var     = new String[5];
	    	      var[0]  = "newSearch";
	    	      val[0]  = "true";
	    	      var[1]  = "locale";
	    	      val[1]  = "nl_BE";
	    	      var[2]  = "phoneNumberSearch";
	    	      val[2]  = "true";
	    	      var[3]  = "what";
	    	      val[3]  = "0" + number.substring(2);
	    	      var[4]  = "submit";
	    	      val[4]  = "submit";
	    	      url     = "http://wittegids.truvo.be/search.ds";
	    	      img     = "";
	    	      expr    = "debug";
	    	      iname   = 1;
	    	      istreet = 2;
	    	      izip    = 3;
	    	      iplace  = 4;
	          }
	          else if (number.startsWith("33"))
	          {
	    	      // France
	    	      country = "France";
	          }
	          else if (number.startsWith("34"))
	          {
	              // Spain
	    	      country = "Spain";
	          }
	          else if (number.startsWith("350"))
	          {
	              // Gibraltar
	    	      country = "Gibraltar";
	          }
	          else if (number.startsWith("351"))
	          {
	           // Portugal
	    	   country = "Portugal";
	       }
	       else if (number.startsWith("352"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("353"))
	       {
	           // Ireland
	    	   country = "Ireland";
	       }
	       else if (number.startsWith("354"))
	       {
	           // Iceland
	    	   country = "Iceland";
	       }
	       else if (number.startsWith("355"))
	       {
	           // Albania
	    	   country = "Albania";
	       }
	       else if (number.startsWith("356"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("357"))
	       {
	           // Cyprus
	    	   country = "Cyprus";
	       }
	       else if (number.startsWith("358"))
	       {
	           // Finland
	    	   country = "Finland";
	       }
	       else if (number.startsWith("359"))
	       {
	           // Bulgaria
	    	   country = "Bulgaria";
	       }
	       else if (number.startsWith("36"))
	       {
	           // Hungary
	    	   country = "Hungary";
	       }
	       else if (number.startsWith("370"))
	       {
	           // Lithuania
	    	   country = "Lithuania";
	       }
	       else if (number.startsWith("371"))
	       {
	           // Latvia
	    	   country = "Latvia";
	       }
	       else if (number.startsWith("372"))
	       {
	           // Estonia
	    	   country = "Estonia";
	       }
	       else if (number.startsWith("373"))
	       {
	           // Moldova
	    	   country = "Moldova";
	       }
	       else if (number.startsWith("374"))
	       {
	           // Armenia
	    	   country = "Armenia";
	       }
	       else if (number.startsWith("375"))
	       {
	           // Luxembourg
	    	   country = "Belarus";
	       }
	       else if (number.startsWith("376"))
	       {
	           // Luxembourg
	    	   country = "Andorra";
	       }
	       else if (number.startsWith("37744"))
	       {
	           // Kosovo
	    	   country = "Kosovo";
	       }
	       else if (number.startsWith("377"))
	       {
	           // Luxembourg
	    	   country = "Monaco";
	       }
	       else if (number.startsWith("378"))
	       {
	           // Luxembourg
	    	   country = "San Marino";
	       }
	       else if (number.startsWith("379"))
	       {
	           // Luxembourg
	    	   country = "Vatican City";
	       }
	       else if (number.startsWith("380"))
	       {
	           // Luxembourg
	    	   country = "Ukraine";
	       }
	       else if (number.startsWith("381"))
	       {
	           // Luxembourg
	    	   country = "Serbia";
	       }
	       else if (number.startsWith("382"))
	       {
	           // Luxembourg
	    	   country = "Montenegro";
	       }
	       else if (number.startsWith("383"))
	       {
	           // Luxembourg
	    	   country = "unassigned";
	       }
	       else if (number.startsWith("384"))
	       {
	           // Luxembourg
	    	   country = "unassigned";
	       }
	       else if (number.startsWith("385"))
	       {
	           // Luxembourg
	    	   country = "Croatia";
	       }
	       else if (number.startsWith("38649"))
	       {
	           // Luxembourg
	    	   country = "Kosovo";
	       }
	       else if (number.startsWith("386"))
	       {
	           // Luxembourg
	    	   country = "Croatia";
	       }
	       else if (number.startsWith("387"))
	       {
	           // Luxembourg
	    	   country = "Bosnia and Herzegovina";
	       }
	       else if (number.startsWith("3883"))
	       {
	           // Luxembourg
	    	   country = "Shared EC";
	       }
	       else if (number.startsWith("388"))
	       {
	           // Luxembourg
	    	   country = "Shared EC";
	       }
	       else if (number.startsWith("389"))
	       {
	           // Luxembourg
	    	   country = "Republic of Macedonia";
	       }
	       else if (number.startsWith("39"))
	       {
	           // Luxembourg
	    	   country = "Italy";
	       }
	       else if (number.startsWith("40"))
	       {
	           // Luxembourg
	    	   country = "Romania";
	       }
	       else if (number.startsWith("41"))
	       {
	           // Luxembourg
	    	   country = "Switzerland";
	       }
	       else if (number.startsWith("420"))
	       {
	           // Luxembourg
	    	   country = "Czech Republic";
	       }
	       else if (number.startsWith("421"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("422"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("423"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("424"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("425"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("426"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("427"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("428"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("429"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("43"))
	       {
	           // Luxembourg
	    	   country = "Austria";
	       }
	       else if (number.startsWith("44"))
	       {
	           // Luxembourg
	    	   country = "United Kingdom";
	       }
	       else if (number.startsWith("45"))
	       {
	    	   // 20, 21, 22, 257, 26, 271, 272, 273, 28, 30, 40, 50, 70, 77, 88, 90, 922
	           // Luxembourg
	    	   String mob[] = {"20","21","22","257","26","271","273","28","30","40","50","70","77","88","90","922"};
	    	   for (String tempmob: mob)
	    	   {
	    		   if (number.startsWith(tempmob,2))
	    		   {
	    			   phone = 'M';
	    			   break;
	    		   }
	    	   }
	    	   
	    	   var= new String[4];
	    	   val= new String[4];
	    	   url = "http://appsrv.118online.dk/cgi-bin/118online.cgi?session=&url=http://193.3.142.101/Scripts/DaiCgi_kosak_udv.exe";
	    	   var[0] = "phone";       
	    	   val[0] = number.substring(2);
	    	   var[1] = "CgiFunction"; 
	    	   val[1] = "PhoneEnquiry";
	    	   var[2] = "SUBMIT";
	    	   val[2] = "Start S&oslash;gning";
	    	   var[3] = "RESET";
	    	   val[3] = "Rens Felter";
	    	   country = "Denmark";
	    	   iso = "DK";   	   

	    	   expr = "</TD>\\s+<TD><FONT SIZE=\"2\" face=\"Arial, Helvetica, sans-serif\">([^<]+)</FONT></TD>" 
	    		              + ".*?<FONT SIZE=\"2\" face=\"Arial, Helvetica, sans-serif\">([^<]+)</FONT></TD>"
	    		              + ".*?<FONT SIZE=\"2\" face=\"Arial, Helvetica, sans-serif\">([^<]+)</FONT></TD>"
	    		              + ".*?<FONT SIZE=\"2\" face=\"Arial, Helvetica, sans-serif\">([^<]+)</FONT></TD>";	    	   
	    	   iname = 1;
	    	   istreet = 2;
	    	   //izip = 3;
	    	   iplace = 3;
	       }
	       else if (number.startsWith("46"))
	       {
	           // Luxembourg
	    	   country = "Sweden";
	       }
	       else if (number.startsWith("47"))
	       {
	           // Luxembourg
	    	   country = "Norway";
	       }
	       else if (number.startsWith("48"))
	       {
	           // Luxembourg
	    	   country = "Poland";
	       }
	       else if (number.startsWith("49"))
	       {
	           // Luxembourg
	    	   //
	    	   // 15x, 16x, 17x
	    	   if (number.startsWith("15", 2) || number.startsWith("16", 2) || number.startsWith("17", 2))
	    	   {
	    		   phone = 'M';
	    	   } 	   
	    	   country = "Germany";
	    	   iso     = "DE";
	    	   url = "http://www.goyellow.de/inverssuche/?TEL=0" + number.substring(2);
	    	   expr = "Detailinformationen zu.*?<span class=\"normal\">([^<]+)</span>.*?<span class=\"street\">([^<]+)</span>.*?<span class=\"postcode\">([^<]+)</span>.*?<span class=\"cityShort\">([^<]+)</span>";	    	   
	    	   iname = 1;
	    	   istreet = 2;
	    	   izip = 3;
	    	   iplace = 4;
	       }
	       else if (number.startsWith("81"))
	       {
	           // Luxembourg
	    	   country = "Japan";
	       }
	       else if (number.startsWith("82"))
	       {
	           // Luxembourg
	    	   country = "South Korea";
	       }
	       else if (number.startsWith("83"))
	       {
	           // Luxembourg
	    	   country = "Luxembourg";
	       }
	       else if (number.startsWith("84"))
	       {
	           // Luxembourg
	    	   country = "Vietnam";
	       }
	       else if (number.startsWith("850"))
	       {
	           // Luxembourg
	    	   country = "North Korea";
	       }
	       else if (number.startsWith("851"))
	       {
	           // Luxembourg
	    	   country = "unassigned";
	       }
	       else if (number.startsWith("852"))
	       {
	           // Luxembourg
	    	   country = "Hong Kong";
	       }
	       else if (number.startsWith("853"))
	       {
	           // Luxembourg
	    	   country = "Macau";
	       }
	       else if (number.startsWith("854"))
	       {
	           // Luxembourg
	    	   country = "unassigned";
	       }
	       else if (number.startsWith("855"))
	       {
	           // Luxembourg
	    	   country = "Cambodia";
	       }
	       else if (number.startsWith("856"))
	       {
	           // Luxembourg
	    	   country = "Laos";
	       }
	       else if (number.startsWith("857"))
	       {
	           // Luxembourg
	    	   country = "unassigned";
	       }
	       else if (number.startsWith("858"))
	       {
	           // Luxembourg
	    	   country = "unassigned";
	       }
	       else if (number.startsWith("859"))
	       {
	           // Luxembourg
	    	   country = "unassigned";
	       }
	       else
	    	   country = "un("+number+")";
	       //local number ?  
	     
	       if (number.compareTo("31577460685") == 0)
	       {
              name = "Home Sweet Home";
	       }   
	    	  
	       if (expr != null)
	       {
	    	  if (val != null)
	    	  {
	    		  // Do a post
	    		  outLine = postURL(url, var, val, resp);
	    	  }
	    	  else 
	    	  {
	    		  // Do a get
	    		  outLine = fetchURL(url);   		  
	    	  }
	    	  
	    	  if (expr == "debug" || req.getParameter("debug") != null)
	    	  {
	    		  resp.getOutputStream().println(outLine);
	    	  }

	    	  if (outLine != null && outLine.length() > 0 && expr != "debug")
	    	  {
	             Pattern patt = Pattern.compile(expr, Pattern.DOTALL | Pattern.UNIX_LINES);
	             Matcher m = patt.matcher(outLine);
	             if (m.find())
	             {
	    	        if (iname > 0)
	    	        {   
	    		       name = m.group(iname);
	    	        }
	    	        if (istreet > 0)
	    	        {
	    		       street = m.group(istreet);
	    	        }
	    	        if (iplace > 0)
	    	        {
	    		       place = m.group(iplace);
	    	        }
	    	        if (izip > 0)
	    	        {
	    		       zip = m.group(izip);
	    	        }
	    	        doOutput(resp.getOutputStream(), output, full, phone, iso, name, street, place, country);
	                sendIM(name);
	             }
	             else
	             {
	    		    ServletOutputStream out = resp.getOutputStream();  
	    		    out.println("("+phone+","+iso+") Not Listed");
	             }	             
	    	  }
	       }
	       else 
	       {
	    	   resp.getOutputStream().println("Not Implemented.");
	       }
	       

	       }
	       else
	       {	      
		       ServletOutputStream out = resp.getOutputStream();  
		       out.println("Hidden");		    	   
	    	   
	       }
	}
	
	public boolean sendIM(String msgBody)
	{
		boolean messageSent = false;
		try 
		{
           JID jid = new JID("anjo.kolk@miraclebenelux.nl");
           Message msg = new MessageBuilder().withRecipientJids(jid).withBody(msgBody).build();
              
           XMPPService xmpp = XMPPServiceFactory.getXMPPService();
           if (xmpp.getPresence(jid).isAvailable()) 
           {
              SendResponse status = xmpp.sendMessage(msg);
              messageSent = (status.getStatusMap().get(jid) == SendResponse.Status.SUCCESS);
           }

           if (!messageSent) 
           {
              // Send an email message instead...
           }
		} 
		catch (XMPPFailureException e)
		{
			messageSent = false;
		}
        return messageSent;
	}
	
	public String findCountry(int numnummer)
	{
		String country = "(??)";
		return country;
	}
	
	public String fetchURL(String p_url)
	{
        try {
            URL url = new URL(p_url);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            String buffer = "";

            while ((line = reader.readLine()) != null) {
                // ..
            	buffer = buffer + line;
            }
            reader.close();
            return buffer;
        } catch (MalformedURLException e) {
            // ...
        	return null;
        } catch (IOException e) {
            // ...
        	return null;
        }	
	}
	
	public void doOutput(ServletOutputStream out, int output, String full, char phone, String iso, String name, String street, String place, String country)
	{
		try
		{
	       if (output == 1)
	       {
	    	  // text
		      if (full == null)
		      {
		        out.println("("+phone+","+iso+") " + name);
		      }
		      else
		      {
	    	    out.println("("+phone+","+iso+") " + name + ", " + street + ", " + place + ", " + country);
		      }
	       }
	       else if (output == 3)
	       {
	    	  out.println("<CALLER><NAME>"+name+"</NAME></CALLER>");
	       }
	       out.flush();
		}
		catch (IOException e)
		{
			return;
		}
		
	}
	
	@SuppressWarnings("deprecation")
	public String postURL(String p_url, String var[], String val[], HttpServletResponse resp) 
	{
		String buffer=null;
		String add="";
		URL                 url;
	    URLConnection       urlConn;
	    DataOutputStream    printout;
	    DataInputStream     input;
	    String              content = "";
	    
	    try {
	    // URL of CGI-Bin script.
	    url = new URL (p_url);
	    // URL connection channel.
	    urlConn = url.openConnection();
	    // Let the run-time system (RTS) know that we want input.
	    urlConn.setDoInput (true);
	    // Let the RTS know that we want to do output.
	    urlConn.setDoOutput (true);
	    // No caching, we want the real thing.
	    urlConn.setUseCaches (false);
	    // Specify the content type.
	    urlConn.setRequestProperty
	    ("Content-Type", "application/x-www-form-urlencoded");
	    // Send POST output.
	    printout = new DataOutputStream (urlConn.getOutputStream ());
	    for (int i = 0; i < val.length; i++)
	    {
	    	// resp.getOutputStream().println(var[i] + "="+val[i]);
	    	if (i > 0)
	    	{
	    		add = "&";
	    	}
	    	String enc = URLEncoder.encode(val[i]);
	    	content = content + add + var[i] +"="+enc;
	    }
	    printout.writeBytes (content);
	    printout.flush ();
	    printout.close ();
	    // Get response data.
	    input = new DataInputStream (urlConn.getInputStream ());
	    String str;
	    // resp.getOutputStream().println("Receiving....");
	    while (null != ((str = input.readLine())))
	    {
	    	// resp.getOutputStream().println("....Line:"+str);
	    	buffer = buffer + str;
	    }
	    input.close ();	
	 } catch (MalformedURLException e) {
         // ...
     	return null;
     } catch (IOException e) {
         // ...
     	return null;
     }	
	    return buffer;	
	}
	
	/*
    public void upload2ocr(URL url, List<File> files) throws Exception
    {
    	http://www.newocr.com/
        HttpURLConnection theUrlConnection = (HttpURLConnection) url.openConnection();
        theUrlConnection.setDoOutput(true);
        theUrlConnection.setDoInput(true);
        theUrlConnection.setUseCaches(false);
        theUrlConnection.setChunkedStreamingMode(1024);

        theUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
                + Boundary);

        DataOutputStream httpOut = new DataOutputStream(theUrlConnection.getOutputStream());

        for (int i = 0; i < files.size(); i++)
        {
            File f = files.get(i);
            String str = "--" + Boundary + "\r\n"
                       + "Content-Disposition: form-data;name=\"file" + i + "\"; filename=\"" + f.getName() + "\"\r\n"
                       + "Content-Type: image/png\r\n"
                       + "\r\n";

            httpOut.write(str.getBytes());

            FileInputStream uploadFileReader = new FileInputStream(f);
            int numBytesToRead = 1024;
            int availableBytesToRead;
            while ((availableBytesToRead = uploadFileReader.available()) > 0)
            {
                byte[] bufferBytesRead;
                bufferBytesRead = availableBytesToRead >= numBytesToRead ? new byte[numBytesToRead]
                        : new byte[availableBytesToRead];
                uploadFileReader.read(bufferBytesRead);
                httpOut.write(bufferBytesRead);
                httpOut.flush();
            }
            httpOut.write(("--" + Boundary + "--\r\n").getBytes());

        }

        httpOut.write(("--" + Boundary + "--\r\n").getBytes());

        httpOut.flush();
        httpOut.close();

        // read & parse the response
        InputStream is = theUrlConnection.getInputStream();
        StringBuilder response = new StringBuilder();
        byte[] respBuffer = new byte[4096];
        while (is.read(respBuffer) >= 0)
        {
            response.append(new String(respBuffer).trim());
        }
        is.close();
        System.out.println(response.toString());
    }
    */
}
